<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/9/9
 * Time: 21:56
 */

namespace App\Handlers\Middleware;


use App\Dictionary;
use TransitService;

class Transit implements MiddlewareInterface
{

    public static $transit;

    public static function fire($message, $keyword = null)
    {

        self::$transit = $transit = Dictionary::transit($keyword);

        $direction = str_contains($message->Content, '出校') ? '出校' : '回校';

        $info = TransitService::getInfo($message->Content, $keyword);

        if($info === false){
            return '公交查询异常，请稍后查询';
        }else{
            list($station, $position) = $info;
        }

        $result = '👣'  . $keyword . "路公交路线\n\n";

        $result = str_finish($result, '🚥当前查询为' . $direction . "方向:\n" . $station['l'][0]['n'] . '→' . end($station['l'])['n'] . "\n\n");

        $result = str_finish($result, "🕒此方向的乘车时间为：\n" . ($direction === '出校' ? $transit['back'] : $transit['out']) . "({$transit['time']})\n\n");

        $result = str_finish($result, self::getFare());

        $result = str_finish($result, "🚉此路线的实时公交状况：\n");

        $result = str_finish($result, self::getTotal($position));

        $result = str_finish($result, self::getPosition($station, $position));

        $result = str_finish($result, $direction === '回校' ? "\n\n💡回复'{$keyword}出校'查询从学校出发方向的实时公交情况" : '');

        $result = str_finish($result, "\n\n计协已开通实时公交查询，可点击菜单“校园”的实时公交查询 <a href='".env('APP_URL') . 'traffic'."'>点击我进行实时公交查询</a>");

        return $result;
    }

    private static function getFare()
    {
        return "💰此路线的乘车费用为：\n" . self::$transit['fare'] . "\n\n";
    }

    private static function getTotal($position)
    {
        $collection = collect($position);

        $sum = $collection->sum(function($item){
            return (count($item['bl']) || count($item['bbl'])) ? 1 : 0;
        });

        return  "\n当前共有{$sum}辆公交车在此方向上运行，🚌所标的站点表示公车即将进入此站，请做好突破人群的准备！\n\n";;
    }

    private static function getPosition($station, $position)
    {
        $result = '';

        foreach ($position as $key => $value) {
            if(count($value['bl']) > 0){
                $result = str_finish($result, '🚌'. $station['l'][$key]['n'] . '→');
            }else{
                $result = str_finish($result, $station['l'][$key]['n'] . '→');
                $result = str_finish($result, count($value['bbl']) > 0 ? '🚌' : '');
            }
        }

        return "【起点】→{$result}【终点】";
    }

}